<template>
  <el-form v-show="getShow" ref="formLogin" :model="loginForm" :rules="LoginRules" class="login-form"
    label-position="top" label-width="120px" size="large">
    <el-row style="maring-left: -10px; maring-right: -10px">
      <el-col :span="24" class="flex justify-center">
        <el-form-item>
          <img :src="getAssetsFile" alt="" />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="flex justify-center">
        <el-form-item>
          <div class="text-lg">运营平台</div>
        </el-form-item>
      </el-col>

      <el-col :span="24" style="padding-left: 10px; padding-right: 10px">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" :placeholder="t('login.usernamePlaceholder')" :maxlength="20">
            <template #prefix>
              <img src="@/assets/imgs/user-icon.png" />
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-left: 10px; padding-right: 10px">
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" :placeholder="t('login.passwordPlaceholder')" show-password
            type="password" :maxlength="16">
            <template #prefix>
              <img src="@/assets/imgs/password-icon.png" />
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-left: 10px; padding-right: 10px; margin-top: -20px; margin-bottom: -20px">
        <el-form-item>
          <el-row justify="space-between" style="width: 100%">
            <el-col :span="6">
              <el-button v-if="props.isShow" type="text" link @click="linkToApplication">{{
                t('login.applyRegistration')
                }}</el-button>
            </el-col>
            <el-col :span="6" class="text-right">
              <el-button type="text" link @click="openForgotPasswordModel">{{
                t('login.forgetPassword')
                }}</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-left: 10px; padding-right: 10px">
        <el-form-item>
          <XButton :loading="loginLoading" :title="t('login.login')" class="w-[100%]" type="primary"
            @click="handleLoginSubmit" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <ForgotPassword ref="forgotPassword"></ForgotPassword>
</template>
<script lang="ts" name="LoginForm" setup>
  import { useRouter } from 'vue-router'
  import { ElLoading } from 'element-plus'
  import type { RouteLocationNormalizedLoaded } from 'vue-router'
  import * as authUtil from '@/utils/auth'
  import { usePermissionStore } from '@/store/modules/permission'
  import * as LoginApi from '@/api/login'
  import ForgotPassword from './forgotPassword.vue'
  import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'
  import { getEnvType } from '@/global'

  const { t } = useI18n()
  const formLogin = ref()
  const { validForm } = useFormValid(formLogin)
  const { getLoginState } = useLoginState()
  const { currentRoute, push } = useRouter()
  const permissionStore = usePermissionStore()
  const redirect = ref < string > ('')
  const loginLoading = ref(false)
  const router = useRouter()
  const forgotPassword = ref()
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false
    }
  })

  const getAssetsFile = computed(() => {
    if (['DEV', 'TEST'].includes(getEnvType())) {
      return new URL('@/assets/imgs/login-logo.png', import.meta.url).href
    }
    if (['YIDONG'].includes(getEnvType())) {
      return new URL('@/assets/imgs/login-logo-yd.png', import.meta.url).href
    }
    if (['HENGYUAN'].includes(getEnvType())) {
      return new URL('@/assets/imgs/login-logo-hy.png', import.meta.url).href
    }
    if (['ZHAOCANGMAO'].includes(getEnvType())) {
      return new URL('@/assets/imgs/login-logo-zcm.png', import.meta.url).href
    }
    if (['GLG'].includes(getEnvType())) {
      return new URL('@/assets/imgs/login-logo-glg.png', import.meta.url).href
    }
    if (['SSP'].includes(getEnvType())) {
      return new URL('@/assets/imgs/login-logo-ssp.png', import.meta.url).href
    }
    return ''
  })

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)

  const LoginRules = {
    username: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      { min: 6, max: 16, message: '密码长度6-16位', trigger: 'blur' }
    ]
  }
  const loginForm: Record<string, any> = ref({
    username: '',
    password: '',
  })

  let timer = null

  const linkToApplication = () => {
    router.push({ path: '/registerJump' })
  }

  const openForgotPasswordModel = () => {
    forgotPassword.value.open(loginForm.value.username)
  }

  // 登录
  const handleLoginSubmit = async () => {
    loginLoading.value = true
    try {
      const data = await validForm()
      if (!data) {
        return
      }
      handleLogin()
    } finally {
      loginLoading.value = false
    }
  }

  const handleLogin = async () => {
    try {
      const res = await LoginApi.login(loginForm.value)
      if (!res) {
        return
      }
      ElLoading.service({
        lock: true,
        text: '正在加载系统中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      authUtil.removeLoginForm()
      authUtil.setToken(res)
      if (!redirect.value) {
        redirect.value = '/'
      }
      push({ path: redirect.value || permissionStore.addRouters[0].path })
    } finally {
      setTimeout(() => {
        const loadingInstance = ElLoading.service()
        loadingInstance.close()
      }, 400)
    }
  }

  watch(
    () => currentRoute.value,
    (route: RouteLocationNormalizedLoaded) => {
      redirect.value = route?.query?.redirect as string
    },
    {
      immediate: true
    }
  )

  onMounted(async () => {
    window.addEventListener('keydown', (e) => {
      if (e.keyCode === 13 || e.keyCode === 32) {
        handleLoginSubmit()
      }
    })
  })

  onBeforeUnmount(() => {
    if (timer) clearInterval(timer)
  })
</script>

<style lang="scss" scoped>
  :deep(.anticon) {
    &:hover {
      color: var(--el-color-primary) !important;
    }
  }

  .login-code {
    width: 100%;
    height: 38px;
    float: right;

    img {
      cursor: pointer;
      width: 100%;
      max-width: 100px;
      height: auto;
      vertical-align: middle;
    }
  }

  .text-lg {
    font-size: 28px;
    font-weight: bold;
  }
</style>